package aufgabe3_chat;

import java.net.DatagramSocket;
import java.net.SocketException;

import aufgabe3_chat.chatGui.ChatFenster;
import aufgabe3_chat.chatGui.Menue;
import aufgabe3_chat.chatGui.Userliste;


public class Client extends Thread{

	Menue menue;
	Chat_User_Administration chat_user;
	Client_TCP client_tcp;
	ChatFenster chatfenster;
	Client_UDP_send send;
	Client_UDP_receive receive;
	Logger logger;
	DatagramSocket udpSocket;
	Userliste userliste;
	final int UDP_PORT = 50001;
	final int TCP_PORT = 50000;
	private final int PACKETSIZE = 1024;
	
	// Broadcast JA oder NEIN
	boolean broadcast = false;
	
	public Client(){
		//UDP Verbindung aufbauen
		try {
			udpSocket = new DatagramSocket(UDP_PORT);
			udpSocket.setBroadcast(broadcast);
		} catch (SocketException e) {
			logger.log("Client", "CLIENT: Verkn�pfung fehlgeschlagen", "Error");
			e.printStackTrace();
		} 

		logger = new Logger();
		chat_user = new Chat_User_Administration(logger);
		logger.log("Client", "Verbindung des UDP_Sockets im CLIENT: ", "" + udpSocket.isConnected());
		userliste = new Userliste();
		client_tcp = new Client_TCP(chat_user, logger, userliste, TCP_PORT);
		menue = new Menue(client_tcp);
		send = new Client_UDP_send(chat_user, udpSocket, client_tcp, logger, PACKETSIZE);
		chatfenster = new ChatFenster(send, client_tcp);
		receive = new Client_UDP_receive(chat_user, chatfenster, udpSocket, logger, PACKETSIZE);
		menue.setVisible(true);
		logger.log("Client", "Alle Objekte da", "Nun werden die Threads gestarted");
		receive.start();
		
	}
	
	public void run(){

		while(menue.isVisible()){
			my_sleep();
		}
		
		my_sleep();
		chatfenster.setVisible(true);
		userliste.setVisible(true);
		
		while(client_tcp.isAlive()){
			my_sleep();
		}
		chatfenster.dispose();
		userliste.dispose();
		logger.log("Client", "Benden", "Abgeschlossen");
	}

	public void my_sleep(){
		try {
			sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
